<template>
  <div class="detail">
    <el-form
      ref="postForm"
      :model="postForm"
      :rules="rules"
      label-position="right"
      label-width="130px"
    >
      <div class="form-data">
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="postForm.title"
            placeholder="标题"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="主图" prop="main_image">
          <image-item
            ref="imageItem"
            v-model="postForm.main_image"
            placeholder="主图"
            style="width: 100%"
            :limit="1"
          />
        </el-form-item>
        <el-form-item label="所属栏目" prop="category_id">
          <el-select
            v-model.number="postForm.category_id"
            placeholder="所属栏目"
            style="width: 100%"
            @change="changeCategoryID"
          >
            <tn-select-group
              :item="categoryOptions"
              label-key="label"
              value-key="id"
              :parent-click="false"
            />
            <!-- <el-option v-for="item in categoryOptions" :key="item.id" :value="item.id" :label="item.title" /> -->
          </el-select>
        </el-form-item>
        <el-form-item label="所属模型" prop="model_id">
          <el-select
            v-model.number="postForm.model_id"
            placeholder="所属模型"
            style="width: 100%"
          >
            <el-option v-for="item in modelOptions" :key="item.id" :value="item.id" :label="item.cn_name + '(' + item.en_name + ')'" />
          </el-select>
        </el-form-item>
        <el-form-item label="查看人数" prop="view_count">
          <el-input-number
            v-model.number="postForm.view_count"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="点赞人数" prop="like_count">
          <el-input-number
            v-model.number="postForm.like_count"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="分享人数" prop="share_count">
          <el-input-number
            v-model.number="postForm.share_count"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="推荐" prop="recomm">
          <el-switch
            v-model.number="postForm.recomm"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model.number="postForm.sort"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model.number="postForm.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>

        <tn-form-item
          v-for="field_item in postForm.fields_data"
          :key="field_item.id+'content'+field_item.en_name"
          v-model="field_item.value"
          :label="field_item.cn_name"
          :name="field_item.en_name"
          :type="field_item.type"
          :tips="field_item.tips"
          :placeholder="'请输入' + field_item.cn_name"
          :multi-select-value="field_item.values !=='' ? field_item.values : []"
          save-dir-name="content_file"
        />
      </div>

      <sticky :class-name="'sub-navbar'">
        <el-button
          v-loading="loading"
          type="success"
          style="margin-left: 10px"
          @click="submitForm"
        >
          {{ isEdit ? '编辑' : '添加' }}
        </el-button>
      </sticky>
    </el-form>
  </div>
</template>

<script>
import Sticky from '@/components/Sticky'
import TnUploadImageItem from '@/components/TNUploadImageItem'
import TnSelectGroup from '@/components/TNSelectGroup'
import TnFormItem from '@/components/TNFormItem'
import { getContentByID, getContentChildrenCountByCategory, addContent, editContent } from '@/api/content'
import { getCategoryAllNode } from '@/api/category'
import { getModelTableAllName, getModelFieldsData } from '@/api/model-table'

const fields = {
  title: '标题',
  main_image: '主图'
}

const validateRequire = (rule, value, callback) => {
  if (!value || value === '' || value.trim() === '') {
    const errMsg = fields[rule.field] + '为必填项'
    callback(new Error(errMsg))
  } else {
    callback()
  }
}

export default {
  name: 'ContentDetail',
  components: { Sticky, 'image-item': TnUploadImageItem, TnSelectGroup, TnFormItem },
  props: {
    id: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      isEdit: false,
      loading: false,
      categoryOptions: [],
      modelOptions: [],
      postForm: {
        title: '',
        main_image: '',
        category_id: '',
        model_id: '',
        table_id: 0,
        view_count: 0,
        like_count: 0,
        share_count: 0,
        recomm: 0,
        fields_data: [],
        sort: 1,
        status: 1
      },
      rules: {
        title: [
          { required: true, message: '标题不能为空' },
          { validator: validateRequire, trigger: 'blur' }
        ],
        main_image: [
          { required: true, message: '主图不能为空' },
          { validator: validateRequire, trigger: 'blur' }
        ],
        model_id: [
          { required: true, message: '所属模型不能为空' },
          { type: 'number', message: '所属模型值格式不正确' }
        ],
        category_id: [
          { required: true, message: '所属栏目不能为空' },
          { type: 'number', message: '所属栏目值格式不正确' }
        ],
        view_count: [
          { required: true, message: '查看人数不能为空' },
          { type: 'number', message: '查看人数值格式不正确' }
        ],
        like_count: [
          { required: true, message: '点赞人数不能为空' },
          { type: 'number', message: '点赞人数值格式不正确' }
        ],
        share_count: [
          { required: true, message: '分享人数不能为空' },
          { type: 'number', message: '分享人数值格式不正确' }
        ],
        recomm: [
          { required: true, message: '推荐不能为空' },
          { type: 'number', message: '推荐值格式不正确' }
        ],
        sort: [
          { required: true, message: '排序不能为空' },
          { type: 'number', message: '排序值格式不正确' }
        ],
        status: [
          { required: true, message: '状态不能为空' },
          { type: 'number', message: '状态值格式不正确' }
        ]
      }
    }
  },
  watch: {
    'postForm.model_id': {
      handler(val) {
        this.getFieldsData(val)
      }
    }
  },
  methods: {
    submitForm() {
      if (!this.loading) {
        this.loading = true
        this.$refs.postForm.validate((valid, fields) => {
          // 判断规则是否通过验证
          if (valid) {
            const content = Object.assign({}, this.postForm)
            // console.log(menu)
            if (!this.isEdit) {
              addContent(content).then(response => {
                this.$notify({
                  title: '成功',
                  message: response.msg,
                  type: 'success',
                  duration: 2000
                })
                this.$emit('ended')
              }).catch(() => {
                this.loading = false
              })
            } else {
              content.id = this.id
              editContent(content).then(response => {
                this.$notify({
                  title: '成功',
                  message: response.msg,
                  type: 'success',
                  duration: 2000
                })
                this.$emit('ended')
              }).catch(() => {
                this.loading = false
              })
            }
          } else {
            this.loading = false
            for (const key in fields) {
              if (fields.hasOwnProperty(key)) {
                const element = fields[key]
                this.$message({
                  message: element[0].message,
                  type: 'error',
                  duration: 2000
                })
                return false
              }
            }
          }
        })
      }
    },
    getContentByID() {
      if (this.id !== 0) {
        getContentByID(this.id).then(response => {
          if (!response.data || response.data.length === 0) {
            this.isEdit = false
            return
          }
          const {
            title,
            main_image,
            category_id,
            model_id,
            table_id,
            view_count,
            like_count,
            share_count,
            recomm,
            fields_data,
            sort,
            status
          } = response.data
          this.postForm = {
            title,
            main_image,
            category_id,
            model_id,
            table_id,
            view_count,
            like_count,
            share_count,
            recomm,
            fields_data,
            sort,
            status
          }
          this.isEdit = true
        }).catch(() => {
          this.isEdit = false
          this.toDefault()
        })
      } else {
        this.isEdit = false
      }
    },
    toDefault() {
      this.$refs.postForm.resetFields()
      this.loading = false
    },
    async getAllNodeData() {
      const category = await getCategoryAllNode()
      const model = await getModelTableAllName()
      this.categoryOptions = category.data
      this.modelOptions = model.data
      this.getContentByID()
    },
    changeCategoryID(value) {
      getContentChildrenCountByCategory(value).then(response => {
        const { count } = response
        this.postForm.sort = count + 1
      })
    },
    getFieldsData(value) {
      getModelFieldsData({
        id: value,
        table_id: this.postForm.table_id
      }).then(response => {
        const { data } = response
        this.postForm.fields_data = data
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
